package com.leilei.autoconfigure;

import com.leilei.support.J2CacheCacheManger;
import net.oschina.j2cache.CacheChannel;
import net.oschina.j2cache.J2Cache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.cache.CacheProperties;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.List;


/**
 * @author lei
 * @create 2022-05-10 15:51
 * @desc 基于j2cache开源代码改造, 开启对spring cache支持的配置入口
 **/
@Configuration
@ConditionalOnClass(J2Cache.class)
@EnableConfigurationProperties({J2CacheConfigProperties.class, CacheProperties.class})
@ConditionalOnProperty(name = "j2cache.open-spring-cache", havingValue = "true", matchIfMissing = true)
@EnableCaching
public class J2CacheSpringCacheAutoConfiguration {

    private final CacheProperties cacheProperties;

    private final J2CacheConfigProperties j2CacheConfig;

    @Autowired
    J2CacheSpringCacheAutoConfiguration(CacheProperties cacheProperties, J2CacheConfigProperties j2CacheConfig) {
        this.cacheProperties = cacheProperties;
        this.j2CacheConfig = j2CacheConfig;
    }


    /**
     * 诸如j2cache中的CacheChannel，因J2CacheCacheManger与spring提供的chacheManager关联了起来，实现了对缓存注解的逻辑处理
     * 例如 CacheAble channel中则根据KEY去查询了一二级缓存
     * @param cacheChannel
     * @return
     */
    @Bean
    @ConditionalOnBean(CacheChannel.class)
    public J2CacheCacheManger cacheManager(CacheChannel cacheChannel) {
        List<String> cacheNames = cacheProperties.getCacheNames();
        J2CacheCacheManger cacheCacheManger = new J2CacheCacheManger(cacheChannel);
        // 根据配置属性决定是否缓存空值 null
        cacheCacheManger.setAllowNullValues(j2CacheConfig.isAllowNullValues());
        cacheCacheManger.setCacheNames(cacheNames);
        return cacheCacheManger;
    }


}
